import {calculatePossibleMoves} from "./Rules.js";
import {TwoPersonRoomBoard} from "../Axios/TwoPerson.js"
import {
    RenderGame,
    renderBoardMarks,
    showGameResultModal,
    RenderChessPieceSelectionBox,
    hideGameResultModal
} from "./Rendering.js"
import {getStateJwtKey} from "../localStorages/localStorageUesrData.js"
import {showToast} from "../Toast.js"


// 当前哪一方移动
// 有三个值：BLACK RED GAME_OVER
let WhichIsCurrentlyMoving = '';


let PiecesData = [];

//初始化棋盘数据渲染
function renderChessboard() {
    RenderGame(PiecesData, handlePieceClick);
}

// 渲染棋子点击后 可以点击的标记点 处理事件
function handlePieceClick(event) {
    const pieceElement = event.target;

    const color = pieceElement.dataset.color;

    if (WhichIsCurrentlyMoving !== color) {
        if (color === 'BLACK') {
            showToast("请等待红方下棋");
            return;
        } else if (color === 'RED') {
            showToast("请等待黑方下棋");
            return;
        }
        // 游戏结束
        return;
    }
    const x = parseInt(pieceElement.dataset.x);
    const y = parseInt(pieceElement.dataset.y);
    const type = pieceElement.dataset.type;
    // 选择棋子时棋子的框渲染
    RenderChessPieceSelectionBox(color, x, y)

    // 标记点点击事件
    function possibleMovesEventListener(moveX, moveY) {
        handlePieceMove(type, color, x, y, moveX, moveY);
        renderChessboard()
    }


    // 渲染标记点
    renderBoardMarks(type, color, x, y, calculatePossibleMoves(type, color, x, y, PiecesData), possibleMovesEventListener);
}

// 游戏结束
function GameOver(color) {
    WhichIsCurrentlyMoving = 'GAME_OVER';
    showGameResultModal(color)
}

//初始化象棋数据
function initPiecesData() {
    TwoPersonRoomBoard().then(data => {
        console.log("初始 data",data)
        let ChessData = data.data.data
        console.log("测试 ChessData",ChessData)

        PiecesData = ChessData.piecesData;
        WhichIsCurrentlyMoving = ChessData.whichIsCurrentlyMoving;
        renderChessboard()
    });

    hideGameResultModal();
}

//修改象棋数据 (移动)
function revisePiecesData(type, color, piecesX, piecesY, newX, newY) {
    let pieceIndex = PiecesData.findIndex(piece =>
        piece.type === type &&
        piece.color === color &&
        piece.x === piecesX &&
        piece.y === piecesY
    );

    PiecesData[pieceIndex] = {
        type: type,
        color: color,
        x: newX,
        y: newY
    };

    WhichIsCurrentlyMoving = WhichIsCurrentlyMoving === 'black' ? 'red' : 'black';
}

//删除象棋数据 （吃子）
function deletePiecesData(type, color, x, y, newX, newY) {

    //
    const piece = PiecesData.find(piece => piece.x === newX && piece.y === newY);


    if (piece.type === "将" || piece.type === "帅") {
        GameOver(color);
    }
    //要删除 PiecesData 中的特定对象，可以使用 JavaScript 的数组方法 filter。
    // 这个方法会创建一个新数组，包含所有不满足指定条件的元素。在这个例子中，我们需要找到并删除与给定类型、颜色和坐标匹配的对象。
    PiecesData = PiecesData.filter(piece => !(piece.x === newX && piece.y === newY));


    revisePiecesData(type, color, x, y, newX, newY);
}


// 移动棋盘
function handlePieceMove(type, color, piecesX, piecesY, moveX, moveY) {
    // 移除之前的选择框
    for (let selectionBox of document.querySelectorAll('.selection-box')) {
        selectionBox.remove();
    }
    //盘标记点
    for (let markBox of document.querySelectorAll('.mark-box')) {
        markBox.remove();
    }

    // 检查目标位置是否有其他棋子
    const targetPieceIndex = PiecesData.findIndex(piece =>
        piece.x === moveX &&
        piece.y === moveY
    );

    if (targetPieceIndex !== -1) {
        // 如果有棋子，就删除
        deletePiecesData(type, color, piecesX, piecesY, moveX, moveY);
    } else {
        revisePiecesData(type, color, piecesX, piecesY, moveX, moveY);
    }

}

// 页面加载完成后渲染棋盘
window.onload = function () {
    // 页面加载完成后，连接WebSocket
    fetchMessages()
    initPiecesData()
    document.getElementById('newRoundBattle').addEventListener('click', initPiecesData);
};

let websocket = null;

// 从服务器获取消息
function fetchMessages() {
    let jwtKey =getStateJwtKey()
    const client = Math.random().toString(36).substr(2);
    console.log(client)
    //连按webSocket节点
    if ('WebSocket' in window) {
        websocket = new WebSocket("/api/chess-rooms/webSocket/" + jwtKey );
    } else {
        alert('您的浏览器不支持WebSocket')

        return;
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        console.log("连接发生错误")
    }

    //连接成功建立的回调方法
    websocket.onopen = function () {
        console.log("WebSocket连接成功")
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        console.log("接收到消息的回调方法")
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("WebSocket连接已关闭")
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }
}


// 发送消息
function send(message) {
    websocket.send(message)
}
